package com.tea.utils;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class SignUtils {
    public static PrivateKey loadPrivateKey() throws Exception {
        // 1. 加载PEM文件
        InputStream keyStream = SignUtils.class.getResourceAsStream("/cert/apiclient_key.pem");
        String keyContent = new String(keyStream.readAllBytes(), StandardCharsets.UTF_8);

        // 2. 清理PEM格式头尾和空格
        keyContent = keyContent
                .replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replaceAll("\\s+", "");

        // 3. 解码Base64并生成私钥
        byte[] decodedKey = Base64.getDecoder().decode(keyContent);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return KeyFactory.getInstance("RSA").generatePrivate(keySpec);
    }

    public static byte[] generateSignature(String signStr, PrivateKey privateKey) throws Exception {
        Signature signer = Signature.getInstance("SHA256withRSA");
        signer.initSign(privateKey);
        signer.update(signStr.getBytes(StandardCharsets.UTF_8));
        return signer.sign();
    }
}
